<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="../common/NavigationLeft.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>固定资产管理系统</title>
<style type="text/css">
.select2-container--open {
	z-index: 9999999
}
</style>
</head>
<body style="height: 100%">
	<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
		<h2 class="page-header">资产列表</h2>
		<div class="row m-b-sm m-t-sm">
			<div class="col-md-1">
				<a>
					<button type="button" id="refresh" class="btn btn-default btn-sm">刷新</button>
				</a>
			</div>

			<form class="form-horizontal" method="post" id="searchForm">
				<%--<s:if test="session.user.role == 0">--%>
				<div class="col-md-5">
					<button class="btn btn-default btn-sm" type="button"
						id="deleteMany_btn">删除</button>
					<button class="btn btn-default btn-sm" id="QRcode_btn"
						type="button">生成二维码</button>
					<a href="to_addAsset.action">
						<button type="button" class="btn btn-default btn-sm"
							id="entry_btn">添加</button>
					</a>
					<button type="button" class="btn btn-default btn-sm"
						id="fileUpload_btn">批量添加</button>
					<button type="button" class="btn btn-default btn-sm"
						id="download_btn" onclick="download();">导出资产表格</button>

				</div>

				<div class="col-md-4 f-r">
					<div class="input-group">
						<input type="text" id="searchTemp" class="form-control"
							value="${temp }" name="temp" placeholder="请输入资产编号/设备型号/使用人"
							style="height: 30px;"> <span class="input-group-btn">
							<button class="btn btn-primary btn-sm" type="button"
								id="search_btn">搜索</button>
							<button class="btn btn-sm" type="button" id="more_search_btn">更多</button>
						</span>
					</div>
				</div>
			</form>

		</div>
		<div class="placeholder"></div>
		<form class="form-horizontal search_table">
			<div class="form-group col-md-4 col-sm-6 col-xs-12">
				<label class="col-sm-4 control-label">采购日期</label>
				<div class="col-sm-8 WdatePicker">
					<input id="buyTime1" class="form-control" type="datetime"
						placeholder="开始时间"
						onclick="WdatePicker({maxDate:'%y-%M-%d || #F{$dp.$D(\'buyTime2\')}'})" />
					- <input id="buyTime2" class="form-control" type="datetime"
						placeholder="结束时间"
						onclick="WdatePicker({minDate:'#F{$dp.$D(\'buyTime1\')}',maxDate:'%y-%M-%d'})" />
				</div>
			</div>
			<div class="form-group col-md-4 col-sm-6 col-xs-12">
				<label class="col-sm-4 control-label">使用日期</label>
				<div class="col-sm-8 WdatePicker">
					<input id="useTime1" class="form-control" type="datetime"
						placeholder="开始时间"
						onclick="WdatePicker({maxDate:'%y-%M-%d||#F{$dp.$D(\'useTime2\')}'})" />
					- <input id="useTime2" class="form-control" type="datetime"
						placeholder="结束时间"
						onclick="WdatePicker({minDate:'#F{$dp.$D(\'useTime1\')}',maxDate:'%y-%M-%d'})" />
				</div>
			</div>
			<div class="form-group col-md-12 text-center m-t-sm">
				<button id="complex_search_btn" type="button"
					class="btn btn-sm btn-primary">查询</button>
				<button id="clear_btn" type="button" class="btn btn-sm btn-default ">清空</button>
			</div>
		</form>
		<form class="form-horizontal" action="genQRcode.action" method="post"
			id="asset_Form" target="_blank">
			<table id="listTable"
				class="table table-bordered table-striped table-hover"
				cellspacing="0">
				<thead>
					<tr>
						<!-- 每行前面的小选择框 -->
						<th><input autocomplete="off" type="checkbox" id="CheckedAll"
							onclick="checkAll()"></th>
						<th>资产编号</th>
						<th>设备名称</th>
						<th>设备型号</th>
						<!-- <th>资产类别</th> -->
						<th class="min-tablet-p dropdown selectdown">
							<div class="table_dropdown dropdown1">
								<a data-toggle="dropdown" class="dropdown-toggle"
									href="javascript:void(0);">资产类别 <span class="caret"></span></a>
								<ul role="menu" class="dropdown-menu">
									<li class="active"><a href="javascript:void(0);">全部</a></li>
									<li value="0"><a href="javascript:void(0);">电子设备</a></li>
									<li value="1"><a href="javascript:void(0);">办公设备</a></li>
								</ul>
							</div>
						</th>
						<th>使用人</th>
						<th class="min-tablet-p dropdown selectdown">
							<div class="table_dropdown dropdown2">
								<a data-toggle="dropdown" class="dropdown-toggle"
									href="javascript:void(0);">资产状态 <span class="caret"></span></a>
								<ul role="menu" class="dropdown-menu">
									<li class="active" ><a href="javascript:void(0);">全部</a></li>
									<li value="1"><a href="javascript:void(0);">备用</a></li>
									<li value="2"><a href="javascript:void(0);">已分配</a></li>
									<li value="3"><a href="javascript:void(0);">使用中</a></li>
									<li value="4"><a href="javascript:void(0);">维修中</a></li>
									<li value="5"><a href="javascript:void(0);">报废</a></li>
								</ul>
							</div>
						</th>
						<th>采购日期</th>
						<th>领用日期</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
				</tbody>

			</table>
		</form>
	</div>
	<div id="batch_import" class="edit-detail layer_panel"
		style="height: 80px; display: none">
		<!-- <form method="post" id="file_upload_form" class="m-t"
			action="fileInputAsset.action">			
			<div class="form-group">
				<label class="col-sm-4 control-label"><span
					class="text-danger">*</span>文件：</label>
				<input  class="row col-sm-6 control-label" type="file" name="fileName" id="file_input" />
			</div>
		</form> -->
	</div>
	<div class="edit-detail layer_panel" id="File_upload_panel">
		<form action="upload.action" method="post" id="uploadFileForm"
			enctype="multipart/form-data">
			<div>
				<label class="col-sm-12 control-label">请选择文件（.csv文件或.xls文件）</label>
			</div>
			<div class="col-sm-12">
				<s:file class="col-sm-12" type="file" name="file" id="file"
					onchange="changeFileName()"></s:file>
			</div>
			<div style="display: none">
				<p class='col-sm-12' style='color: red'>请选择文件!</p>
			</div>
			<input type="hidden" id="fileName" name="fileName" value="" />
		</form>
	</div>
	<div class="edit-detail layer_panel" id="assignToUser_panel">
		<label>选择使用人</label> <select id="userId" name="userId" lang="zh-CN"
			class="select2" style="width: 100%;">
		</select>
	</div>
	<div class="edit-detail layer_panel" id="receviceTime"
		style="text-align: center">
		<label class="col-sm-12 control-label">请选择领用时间:</label> 
		<input type="text" name="asset.receiveTime" onFocus="WdatePicker({el:'receiveTime_input',dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d'})"
			value="<s:date name="asset.receiveTime "/>" id="receiveTime_input" />
		<img onclick="WdatePicker({el:'receiveTime_input',dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d'})"
			src="/static/js/My97DatePicker/skin/datePicker.gif" width="16" height="22" align="absmiddle">
	</div>
	<div class="edit-detail layer_panel" id="revertTime"
		style="margin-left: 70px">
		<label>请选择设备状况:</label>
		<div>
			<s:select list="#{0:'-请选择-',1:'良好',2:'损坏,需维修',3:'损坏,已报废'}"
				listKey="key" listValue="value" id="optestate"
				name="assetUseHistory.equipState" />
		</div>
		<br> <label>请选择归还时间:</label> 
		<input type="text" name="assetUseHistory.revertTime" onFocus="WdatePicker({el:'receiveTime_input',dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d'})" 
		value="<s:date name="assetUseHistory.revertTime " />" id="revertTime_input" /> <img
			onclick="WdatePicker({el:'revertTime_input',dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d'})"
			src="/static/js/My97DatePicker/skin/datePicker.gif" width="16" height="22" align="absmiddle">
	</div>

	<input id="userRole" type="hidden" value="${session.user.role}">
</body>
<script type="text/javascript">


$(function(){
	var table = "";
	initTable();
	var select2;
	$("#search_btn").click(function(){
		 initTable();
	});
	
	$("#complex_search_btn").click(function(){
		initTable();
	});
	 
	$("#clear_btn").click(function(){
		 $(".search_table input").each(function(){
			 $(this).val(""); 
		 })		
	});
	$("#refresh").click(function(){
		initTable();
	});
    
	//一个class中可以有多个类，中间用空格隔开
	$(document).on("click",".dropdown1 .dropdown-menu a",function(){
		$(this).parent().addClass("active").siblings().removeClass('active');
		$(".table_dropdown").removeClass("open");
		var equipGenre = $(this).parent().attr("value");
		var status = $(".dropdown2 .dropdown-menu li[class='active']").attr("value");
		initTable(equipGenre,status);	
	});
	
	$(document).on("click",".dropdown2 .dropdown-menu a",function(){
		$(this).parent().addClass("active").siblings().removeClass('active');
		$(".table_dropdown").removeClass("open");
		var status = $(this).parent().attr("value");
		var equipGenre = $(".dropdown1 .dropdown-menu li[class='active']").attr("value");
		initTable(equipGenre,status);
	});

    $(".search_table").hide();
    $("#more_search_btn").click(function(){
        $(".search_table").toggle();
    });
    
	//初始化表格的方法，上面的事件中调用该方法
	function initTable(equipGenre,status) {
		var temp = $("#searchTemp").val(); 
		var buyTime1 = $("#buyTime1").val(); 
		var buyTime2 = $("#buyTime2").val(); 
		var useTime1 = $("#useTime1").val(); 
		var useTime2 = $("#useTime2").val(); 
		$.fn.dataTable.ext.errMode = function(s,h,m){
            layer.alert('数据加载失败');
        }
		 table = $('#listTable').DataTable( {
			 "destroy" : true,
			"paging" : true,
			"lengthChange" : true,
			"searching" : false,
			"ordering" : false,
			"info" : true,
			"autoWidth" : false,
			"Filter" : false,
			responsive : true,
			"pagingType" : "full_numbers",
			"dom" : 'rtilp',
			"language" : {
				"url" : "/static/js/datatables/jquery.dataTables.zh"
			},
	        "processing": true,
	        "serverSide": true,
	        "ajax": {
	   	          type: 'POST',  
	   	          url: 'ajax_listAllAssetData.action',  
	   	       	  data:{"temp":temp,"equipGenre":equipGenre,"status":status,"buyTime1":buyTime1,"buyTime2":buyTime2,"useTime1":useTime1,"useTime2":useTime2}, 
	   	          timeout:60000  
	   	      },
	   	      
	   	      //drawCallback函数的意思是只有页面将该行数据加载出来的时候才对该行数据进行以下事件的绑定
             "drawCallback":function () {
            	 $(".Del_li").click(function() {
					 var assetId = $(this).attr("assetId");
            			layer.confirm('确认删除该设备？', {
            				icon : 3,
            				title : '删除设备'
            			}, function(index) {
            				 layer.close(index);
	            				$.ajax({
	                				type : 'POST',
	                				url : 'ajax_deleteAsset.action',
	                				data : {
	                					"id" : assetId
	                				},
	                				success : function(result) {
	                					if (result.operaRes == "1") {
	                						 table.page(table.page()).draw(false);
	                						 layer.msg("删除成功");
	                					} else {
	                						 table.page(table.page()).draw(false);	
	                						 layer.msg("删除失败");
	                					}
	                				},
	                				error : function(){
	                					table.page(table.page()).draw(false);	
               						    layer.msg("删除失败,系统错误");
	                				}
	                			}); 
            		    	});
            	});
            	 
			  $(".assign_li").click(function () {					 
                     var assetId = $(this).attr("assetId");
                     $.ajax({
                         type : 'POST',
                         url : 'ajax_ListUserData.action',
                         data : {
                         },
                         //此处成功的话，输出的是一个用户下拉选择框
                         success : function(result) {
                             //此处的select2是一个插件，与上面的class为select2无关
                        	 $("#userId").select2(
                                 {
                                     language: "zh-CN",
                                     placeholder:"请选择",
                                     data:result,
                                 }
                             );
                             var userId = $("#userId").val();
							 $("#userId").on('select2:select', function (evt) {
                                 userId = $("#userId").val();
                             });
                             layer.open({
                                 title: '选择使用人',
                                 type: 1,
                                 area: ['400px','200px'],
                                 content: $("#assignToUser_panel"),
                                 btn: ['确定', '取消'],
                                 //yes是插件layer的返回方法，同ajax的success的返回方法
                                 yes: function(index, layero) {
                                     layer.close(index);
                                     $.ajax({
                                         type : 'POST',
                                         url : 'ajax_assignAsset.action',
                                         data : {                                   	 
                                             //每行数据的id                              
                                             "id" : assetId,
                                             //用户的id
                                             "userId" : userId
                                         },
                                         success : function(result) {
                                        	 if(result.operaRes == "1"){
                                        		 table.page(table.page()).draw(false);
                                                 layer.msg("分配成功"); 
                                        	 }else{
                                        		 table.page(table.page()).draw(false);
                                                 layer.msg("分配失败"); 
                                        	 }
                                        	                                           
                                         },
                                         error:function () {
                                        	 table.page(table.page()).draw(false);
                                             layer.msg("分配失败,系统错误");                                             
                                         }

                                     });
                                 },
                                 cancel: function(index) {}
                             });
                         },
                         error:function () {
                             layer.alert("分配失败");
                         }
                     });                
				 });
			  
			  $(".receive_li").click(function(){
             	 var assetId = $(this).attr("assetId");
             	 layer.open({
                     title: '领用设备',
                     type: 1,
                     area: ['300px','200px'],
                     content: $("#receviceTime"),
                     btn: ['确定', '取消'],
                     yes: function(index, layero){
                    	 layer.close(index);
                    	 var receiveTime = $("#receiveTime_input").val();
                    	 $.ajax({
             				type : 'POST',
             				url : 'ajax_receiveAsset.action',
             				data : {
             					"id" : assetId,
             					"receiveTime" : receiveTime
             				},
             				success : function(result) {	
             					if(result.operaRes == "1"){
             						table.page(table.page()).draw(false);
              						layer.msg('领用成功');
             					}else{
             						table.page(table.page()).draw(false);
              						layer.msg('领用失败');
             					}
             					   
             				},
             				error:function () {
             					 table.page(table.page()).draw(false);
                                 layer.msg("领用失败,系统错误");
                                     },
             				});	
                    	 }               	 
      		    	});
				 });

				
				 $(".revert_li").click(function(){
					 var assetId = $(this).attr("assetId");
					 layer.open({
                         title: '归还设备',
                         type: 1,
                         area: ['350px','250px'],
                         content: $("#revertTime"),
                         btn: ['确定', '取消'],
                         //yes是插件layer的返回方法，同ajax的success的返回方法
                         yes: function(index, layero) {
                        	 layer.close(index);
                        	 var optestate = $("#optestate").val();//此处拿到的是listKey值
                        	 var revertTime = $("#revertTime_input").val();
        	            				$.ajax({
        	                				type : 'POST',
        	                				url : 'ajax_revertAsset.action',
        	                				data : {
        	                					"id" : assetId,
        	                				    "optestate" : optestate,
        	                				    "revertTime" : revertTime
        	                				},
        	                				success : function(result) {
        	                					if (result.operaRes == "1") {
        	                						table.page(table.page()).draw(false);
        	                						layer.msg('归还成功');
        	                					} else {
        	                						table.page(table.page()).draw(false);
        	                						layer.msg('归还失败');
        	                					}
        	                				},
        	                				error : function(){
        	                					table.page(table.page()).draw(false);
    	                						layer.msg('归还失败,系统错误');
        	                				}
        	                		});
                 			   }	                       
                     });
                 });			
             },
	        "columns" : [
							{
								"data" : function(data) {
										return '<input autocomplete="off" name="checkedIds" type="checkbox" value="'+ data.id+'">';
								}
							},							
							{
								"data" : function(data) {
									if(data.equipIdentifier != null){
										return '<span><a href="assetInfo.action?id='+data.id+'">'+data.equipIdentifier+'</a></span>';
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.equipName != null){
										return data.equipName;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.equipModel != null){
										return data.equipModel;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.equipGenre != null){
										return data.equipGenre;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.usePerson != null){
										return data.usePerson;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.status != null){
										return data.status;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.buyTime != null){
										/* var now = new Date(data.buyTime);
										var nowStr = now.format("yyyy-MM-dd hh:mm:ss"); */
										return data.buyTime;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data) {
									if(data.receiveTime != null){
										return data.receiveTime;
									}else{
										return "--";
									}
								}
							},
							{
								"data" : function(data){
									var modifyOpe ="";
									var deleteOpe = "";
									var assignOpe = "";
									var receiveOpe = "";
									var revertOpe = "";
									/* 在session会话中的到登陆者身份 */
									var userRole = $("#userRole").val();

									if(userRole == "0"){
										modifyOpe = '<li><a class="" href="to_addAsset.action?id='+data.id+'" onclick="">修改</a></li>';
										if(data.status == "备用"){
											assignOpe = '<li><a class="assign_li" href="javascript:void(0);" assetId="'+data.id+'">分配</a></li>';
										}
										
										if(data.status == "已分配"){
										    receiveOpe = '<li><a class="receive_li" href="javascript:void(0);" assetId="'+data.id+'">领用</a></li>';
											revertOpe = '<li><a class="revert_li" href="javascript:void(0);" assetId="'+data.id+'">归还</a></li>';
										}
										if(data.status == "使用中"){
											revertOpe = '<li><a class="revert_li" href="javascript:void(0);" assetId="'+data.id+'">归还</a></li>';
										}
										
										deleteOpe = '<li><a class="Del_li" href="javascript:void(0);" assetId="'+data.id+'">删除</a></li>';
									}
									return '<div class="btn-group">'+
									'<button data-toggle="dropdown"'+
										'class="btn btn-primary btn-xs dropdown-toggle" type="button">'+
										'<i class="fa fa-cog"></i> 操作 <span class="caret"></span>'+
									'</button>'+
									'<ul class="dropdown-menu">'+
										'<li><a class="" href="assetInfo.action?id='+data.id+'">查看</a></li>'+												
											modifyOpe + assignOpe + receiveOpe + revertOpe + deleteOpe;
									'</ul>'+
								'</div>';
								}
							}							
					]
               });
		return table;
	}
});

$(function(){
	var userRole = $("#userRole").val();
	if(userRole == "1"){
		$("#deleteMany_btn").attr("disabled","disabled");
		$("#QRcode_btn").attr("disabled","disabled");
		$("#entry_btn").attr("disabled","disabled");
		$("#fileUpload_btn").attr("disabled","disabled");
		$("#download_btn").attr("disabled","disabled");
	}
});

$(function(){
	var tip="${tip}";
	if(tip!=""){
		layer.msg(tip,{area: ['300px','50px']});
	}
	
	$("#QRcode_btn").click(function() {
		var checkboxlen = 0;
		$("td :checkbox").each(function(index, ele) {
			if ($(this).prop("checked")) {
				checkboxlen++; 
			}
		});
		if(checkboxlen<1){
			layer.msg("至少勾选一项");
		}else{
			$("#asset_Form").submit();
		}
	});	
});

//导出资产信息，为Excel格式
function download(){
	window.location.href="exportAssetExcel.action";
}
	//删除多个
	$("#deleteMany_btn").click(function() {
		var ids = selectIds();
			layer.confirm('确认删除选中的设备？', {
				icon : 3,
				title : '删除设备'
			}, function(index) {
				 layer.close(index);
					$.ajax({
						type : 'POST',
						url : 'ajax_deleteAssetMany.action',
						data : {
							"ids" : ids
						},
						success : function(result) {
							if(result.operaRes == "1"){
								window.location.reload();
							}else{
								$("#search_btn").click();
								layer.msg("删除失败");
							}
							
						},
						error : function(){
							$("#search_btn").click();
							layer.msg("删除失败,系统错误");
						}
					});
		    	});
	})
	//定义的方法：点击最上面的选择框，即把整个选择框全部选取
	function checkAll() {
		if ($("#CheckedAll").prop("checked")) {
			$(":checkbox").prop("checked", true);
		} else {
			$(":checkbox").prop("checked", false);
		}s
	}
	//定义的方法：点击选择框，迭代出id
	function selectIds() {
		var assIds = new Array();
		var idString = "";
		$("td :checkbox").each(function(index, ele) {
			if ($(this).prop("checked")) {
				assIds.push($(this).attr("value"));
			}
		})
		for (var i = 0; i < assIds.length; i++) {
			idString = assIds[i] + "," + idString;
		}
		return idString;
	}
	
	//定义的方法：选择文件
	function changeFileName(){
		var filePath = $("#file").val();
		var fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
		$("#fileName").val(fileName);
		$("#file").parent().next().hide();
	}
	
	$("#fileUpload_btn").click(function(){		
		layer.open({
            title: '文件批量导入',
            type: 1,
            area: ['400px','200px'],
            content: $("#File_upload_panel"),
            btn: ['确定', '取消'],
            yes: function(index, layero) {
            	    if($("#file").val()!=''){
                        $("#uploadFileForm").submit();                      
            	    }
            	    else{
            	    	$("#file").parent().next().show();
            	    }
            	},              
            cancel: function(index) {}
        });
	});
	
	//对Date的扩展，将Date转化为指定格式的String
	Date.prototype.format = function(format){
		var o = {
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(), //day
		"h+" : this.getHours(), //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter 季度
		"S" : this.getMilliseconds() //millisecond 毫秒
		}

		if(/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
		}

		for(var k in o) {
			if(new RegExp("("+ k +")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
			}
		}
		return format;
	} 
</script>
</html>